package net.huashitong.ssydt.provider.gexin.service;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.uitls.LangUtil;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import net.huashitong.ssydt.exceptions.ServiceException;
import net.huashitong.ssydt.gexin.entity.SsPushGetui;
import net.huashitong.ssydt.provider.gexin.config.GetuiConfig;
import net.huashitong.ssydt.provider.gexin.util.TemplateUtils;
import net.huashitong.ssydt.provider.push.PushMessage;
import net.huashitong.ssydt.provider.push.service.PushService;
import net.huashitong.ssydt.provider.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.10.09
 */
@Service
@Transactional
public class GetuiPushService implements PushService {

    private GetuiConfig getuiConfig;

    private SsPushGetuiService ssPushGetuiService;

    private static final long DEFULT_OFFLINE_EXPIRE_TIME = 24 * 3600 * 1000;

    @Autowired
    public GetuiPushService(GetuiConfig getuiConfig, SsPushGetuiService ssPushGetuiService) {
        this.getuiConfig = getuiConfig;
        this.ssPushGetuiService = ssPushGetuiService;
    }

    @Override
    public String pushMessageToSingle(String userId, PushMessage pushMessage) {
        return this.pushMessageToSingle(userId, pushMessage, DEFULT_OFFLINE_EXPIRE_TIME);
    }

    @Override
    public String pushMessageToApp(PushMessage pushMessage) {
        return this.pushMessageToApp(pushMessage, DEFULT_OFFLINE_EXPIRE_TIME);
    }

    @Override
    public String pushMessageToSingle(String userId, PushMessage pushMessage, long offlineExpireTime) {
        String clientid = getClientid(userId);
        if (StringUtils.isBlank(clientid)) {
            return "";
        }

        IGtPush push = new IGtPush(GetuiConfig.HOST, getuiConfig.getAppKey(), getuiConfig.getMasterSecret());
        TransmissionTemplate template = TemplateUtils.getTransmissionTemplate(pushMessage, getuiConfig.getAppId(), getuiConfig.getAppKey());

        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(offlineExpireTime);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);

        Target target = new Target();
        target.setAppId(getuiConfig.getAppId());
        target.setClientId(clientid);
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            return getTaskId(ret);
        } else {
            throw new ServiceException("推送发送失败");
        }
    }

    private String getTaskId(IPushResult ret) {
        if (ret.getResponse() != null) {
            Object taskId = ret.getResponse().containsKey("taskId") ? ret.getResponse().get("taskId") : ret.getResponse().get("contentId");
            return LangUtil.parseString(taskId);
        } else {
            return null;
        }
    }

    /**
     * 获取 clientid
     *
     * @param userId
     * @return
     */
    private String getClientid(String userId) {
        SsPushGetui ssPushGetui = ssPushGetuiService.getByUserId(userId);
        if (ssPushGetui == null) {
            return null;
        }
        return ssPushGetui.getClientid();
    }

    @Override
    public String pushMessageToApp(PushMessage pushMessage, long offlineExpireTime) {
        IGtPush push = new IGtPush(GetuiConfig.HOST, getuiConfig.getAppKey(), getuiConfig.getMasterSecret());
        TransmissionTemplate template = TemplateUtils.getTransmissionTemplate(pushMessage, getuiConfig.getAppId(), getuiConfig.getAppKey());

        List<String> appIdList = new ArrayList<>();
        appIdList.add(getuiConfig.getAppId());
//
//        //推送给App的目标用户需要满足的条件
//        AppConditions cdt = new AppConditions();
//        //手机类型
//        List<String> phoneTypeList = new ArrayList<>();
//        //省份
//        List<String> provinceList = new ArrayList<>();
//        //自定义tag
//        List<String> tagList = new ArrayList<>();
//
//        cdt.addCondition(AppConditions.PHONE_TYPE, phoneTypeList);
//        cdt.addCondition(AppConditions.REGION, provinceList);
//        cdt.addCondition(AppConditions.TAG, tagList);

        AppMessage message = new AppMessage();
        message.setData(template);
        message.setOffline(true);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(offlineExpireTime);
        message.setAppIdList(appIdList);
//        message.setConditions(cdt);

        IPushResult ret = push.pushMessageToApp(message, pushMessage.getMessageId().toString());
        return getTaskId(ret);

    }

    @Override
    public boolean stop(String taskid) {
        IGtPush push = new IGtPush(GetuiConfig.HOST, getuiConfig.getAppKey(), getuiConfig.getMasterSecret());
        return push.stop(taskid);
    }
}
